package reflect;

import org.junit.Test;

import java.util.Random;

/*
* 通过反射创建对应的运行时类的对象
* */
public class NewInstanceTest {

    @Test
    public void test1() throws IllegalAccessException, InstantiationException {
        Class clazz = Person.class;

        /*
        * newInstance().:调用此方法,创建对应的运行时类的对象,内部调用了运行时类的空参构造器
        * 使用此方法:
        *   1:运行时类必须提供空参构造器
        *   2:空参构造器的访问权限得够,通常设置为public
        *
        * 在javabean中要求提供一个空参构造器,原因:
        *   1:便于通过反射,创建运行时类的对象
        *   2:便于子类继承此运行时类时,默认调用super()时,保证父类有此构造器
        * */
        Object o = clazz.newInstance();
        System.out.println(o);//Person{name='null', age=0}

    }

    @Test
    public void test2() throws IllegalAccessException, InstantiationException, ClassNotFoundException {
        for (int i = 0; i <100; i++) {
            Random random = new Random();
            int z = random.nextInt(2);
            switch (z){
                case 0:
                    Object o = newInstance("java.util.Date");
                    break;
                case 1:
                    Object o1 = newInstance("reflect.Person");

                    break;
                case 2:
                    break;
            }
        }
    }

    //通过完整类名路径创建对应的类的对象
    public Object newInstance(String classPath) throws ClassNotFoundException, IllegalAccessException, InstantiationException {
        Class clazz = Class.forName(classPath);
        Object o = clazz.newInstance();
        System.out.println(o);
        return o;
    }

}
